{% extends "layout.html" %}

{% block title %}图片素材搜索{% endblock %}

{% block css %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/picture.css') }}">
{% endblock %}

{% block page_title %}图片素材搜索{% endblock %}

{% block content %}
<div class="picture-container" id="picture-container">
    <div class="picture-header">
        <div class="picture-logo">
            <i class="fas fa-images logo-icon"></i>
            <h1>免费素材</h1>
        </div>
    </div>

    <div class="search-box">
        <input type="text" id="search-input" placeholder="搜索图片素材...">
        <button id="search-button">
            <i class="fas fa-search"></i>
        </button>
    </div>
    
    <!-- 加载状态 -->
    <div class="loading-container" id="loading-container" style="display: none;">
        <div class="loading-spinner"></div>
        <p>正在搜索图片...</p>
    </div>
    
    <!-- 错误信息 -->
    <div class="error-message" id="error-message" style="display: none;"></div>
    
    <!-- 搜索结果 -->
    <div class="image-results" id="image-results" style="display: none;">
        <div class="results-info" id="results-info"></div>
        <div class="image-grid" id="image-grid"></div>
        
        <!-- 分页控件 -->
        <div class="pagination" id="pagination" style="display: none;">
            <button class="pagination-button prev" id="prev-page">
                <i class="fas fa-chevron-left"></i> 上一页
            </button>
            <div class="page-number" id="page-number"></div>
            <button class="pagination-button next" id="next-page">
                下一页 <i class="fas fa-chevron-right"></i>
            </button>
        </div>
    </div>
    
    <!-- 没有结果 -->
    <div class="no-results" id="no-results" style="display: none;">
        没有找到匹配的图片素材，请尝试其他关键词
    </div>
    
    <!-- 图片预览模态框 -->
    <div class="image-preview-modal" id="preview-modal" style="display: none;">
        <div class="image-preview-container">
            <div class="preview-header">
                <span class="preview-title" id="preview-title"></span>
                <button class="close-button" id="close-preview">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="preview-body">
                <button class="nav-button prev" id="preview-prev">
                    <i class="fas fa-chevron-left"></i>
                </button>
                
                <div class="preview-image" id="preview-image"></div>
                
                <button class="nav-button next" id="preview-next">
                    <i class="fas fa-chevron-right"></i>
                </button>
            </div>
            
            <div class="preview-footer">
                <div class="image-details" id="preview-details"></div>
                <button class="download-button" id="download-button">
                    <i class="fas fa-download"></i> 下载原图
                </button>
            </div>
        </div>
    </div>
    
    <!-- 长按菜单 -->
    <div class="long-press-menu" id="long-press-menu" style="display: none;">
        <div class="menu-item" id="long-press-download">
            <i class="fas fa-download"></i> 下载原图
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取DOM元素
        const pictureContainer = document.getElementById('picture-container');
        const searchInput = document.getElementById('search-input');
        const searchButton = document.getElementById('search-button');
        const loadingContainer = document.getElementById('loading-container');
        const errorMessage = document.getElementById('error-message');
        const imageResults = document.getElementById('image-results');
        const imageGrid = document.getElementById('image-grid');
        const resultsInfo = document.getElementById('results-info');
        const pagination = document.getElementById('pagination');
        const noResults = document.getElementById('no-results');
        const previewModal = document.getElementById('preview-modal');
        const previewTitle = document.getElementById('preview-title');
        const previewImage = document.getElementById('preview-image');
        const previewDetails = document.getElementById('preview-details');
        const downloadButton = document.getElementById('download-button');
        const longPressMenu = document.getElementById('long-press-menu');
        
        // 搜索状态变量
        let currentQuery = '';
        let currentPage = 1;
        let pageSize = 20;
        let totalPages = 0;
        let images = [];
        let currentPreviewIndex = 0;
        let longPressTimer = null;
        let currentLongPressImage = null;
        
        // 搜索按钮点击事件
        searchButton.addEventListener('click', performSearch);
        
        // 搜索输入框回车事件
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
        
        // 执行搜索
        function performSearch() {
            const query = searchInput.value.trim();
            if (!query) {
                showError('请输入搜索关键词');
                return;
            }
            
            currentQuery = query;
            currentPage = 1;
            searchImages();
        }
        
        // 搜索图片
        function searchImages() {
            showLoading();
            
            fetch(`/picture/search?q=${encodeURIComponent(currentQuery)}&page=${currentPage}&per_page=${pageSize}`)
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(data => {
                            throw new Error(data.error || '搜索请求失败');
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    if (data.hits && data.hits.length > 0) {
                        images = data.hits;
                        renderSearchResults(data);
                    } else {
                        showNoResults();
                    }
                })
                .catch(error => {
                    hideLoading();
                    showError(error.message);
                });
        }
        
        // 渲染搜索结果
        function renderSearchResults(data) {
            errorMessage.style.display = 'none';
            noResults.style.display = 'none';
            imageResults.style.display = 'block';
            
            // 显示结果信息
            resultsInfo.textContent = `找到 ${data.totalHits} 张相关图片`;
            
            // 清空并渲染图片网格
            imageGrid.innerHTML = '';
            images.forEach((image, index) => {
                const imageItem = createImageItem(image, index);
                imageGrid.appendChild(imageItem);
            });
            
            // 更新分页
            totalPages = Math.ceil(data.totalHits / pageSize);
            updatePagination();
        }
        
        // 创建图片项
        function createImageItem(image, index) {
            const imageItem = document.createElement('div');
            imageItem.className = 'image-item';
            
            imageItem.innerHTML = `
                <div class="image-thumbnail">
                    <img src="${image.previewURL}" alt="${image.tags}" loading="lazy">
                </div>
                <div class="image-info">
                    <div class="image-user">
                        <img src="${image.userImageURL || '/static/images/default-avatar.png'}" alt="${image.user}" class="user-avatar">
                        <span>${image.user}</span>
                    </div>
                    <div class="image-stats">
                        <span><i class="fas fa-eye"></i> ${image.views}</span>
                        <span><i class="fas fa-thumbs-up"></i> ${image.likes}</span>
                    </div>
                </div>
            `;
            
            // 点击预览
            imageItem.addEventListener('click', () => {
                if (!longPressTimer) {
                    openPreview(index);
                }
            });
            
            // 长按事件
            setupLongPress(imageItem, image);
            
            return imageItem;
        }
        
        // 设置长按事件
        function setupLongPress(element, image) {
            function startLongPress(e) {
                e.preventDefault();
                const touch = e.touches ? e.touches[0] : e;
                
                longPressTimer = setTimeout(() => {
                    currentLongPressImage = image;
                    longPressMenu.style.display = 'block';
                    longPressMenu.style.top = `${touch.clientY}px`;
                    longPressMenu.style.left = `${touch.clientX}px`;
                }, 800);
            }
            
            function clearLongPress() {
                clearTimeout(longPressTimer);
                longPressTimer = null;
            }
            
            element.addEventListener('mousedown', startLongPress);
            element.addEventListener('mouseup', clearLongPress);
            element.addEventListener('mouseleave', clearLongPress);
            element.addEventListener('touchstart', startLongPress);
            element.addEventListener('touchend', clearLongPress);
            element.addEventListener('touchcancel', clearLongPress);
        }
        
        // 打开预览
        function openPreview(index) {
            currentPreviewIndex = index;
            const image = images[index];
            
            previewTitle.textContent = `图片预览 (${index + 1}/${images.length})`;
            previewImage.innerHTML = `<img src="${image.webformatURL}" alt="${image.tags}">`;
            previewDetails.innerHTML = `
                <div class="detail-item"><i class="fas fa-user"></i> ${image.user}</div>
                <div class="detail-item"><i class="fas fa-eye"></i> ${image.views}</div>
                <div class="detail-item"><i class="fas fa-thumbs-up"></i> ${image.likes}</div>
                <div class="detail-item"><i class="fas fa-download"></i> ${image.downloads}</div>
            `;
            
            previewModal.style.display = 'block';
            document.body.style.overflow = 'hidden';
            
            updatePreviewNavigation();
        }
        
        // 更新预览导航按钮状态
        function updatePreviewNavigation() {
            document.getElementById('preview-prev').style.display = 
                currentPreviewIndex > 0 ? 'block' : 'none';
            document.getElementById('preview-next').style.display = 
                currentPreviewIndex < images.length - 1 ? 'block' : 'none';
        }
        
        // 关闭预览
        document.getElementById('close-preview').addEventListener('click', () => {
            previewModal.style.display = 'none';
            document.body.style.overflow = '';
        });
        
        // 预览导航
        document.getElementById('preview-prev').addEventListener('click', () => {
            if (currentPreviewIndex > 0) {
                openPreview(currentPreviewIndex - 1);
            }
        });
        
        document.getElementById('preview-next').addEventListener('click', () => {
            if (currentPreviewIndex < images.length - 1) {
                openPreview(currentPreviewIndex + 1);
            }
        });
        
        // 下载图片
        function downloadImage(image) {
            const link = document.createElement('a');
            link.href = image.largeImageURL;
            link.download = `pixabay-${image.id}.jpg`;
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            longPressMenu.style.display = 'none';
        }
        
        downloadButton.addEventListener('click', () => {
            downloadImage(images[currentPreviewIndex]);
        });
        
        document.getElementById('long-press-download').addEventListener('click', () => {
            if (currentLongPressImage) {
                downloadImage(currentLongPressImage);
            }
        });
        
        // 点击空白处关闭长按菜单
        document.addEventListener('click', (e) => {
            if (!e.target.closest('.long-press-menu')) {
                longPressMenu.style.display = 'none';
            }
        });
        
        // 键盘导航
        document.addEventListener('keydown', (e) => {
            if (previewModal.style.display === 'block') {
                switch (e.key) {
                    case 'ArrowLeft':
                        if (currentPreviewIndex > 0) {
                            openPreview(currentPreviewIndex - 1);
                        }
                        break;
                    case 'ArrowRight':
                        if (currentPreviewIndex < images.length - 1) {
                            openPreview(currentPreviewIndex + 1);
                        }
                        break;
                    case 'Escape':
                        previewModal.style.display = 'none';
                        document.body.style.overflow = '';
                        break;
                }
            }
        });
        
        // 更新分页
        function updatePagination() {
            if (totalPages <= 1) {
                pagination.style.display = 'none';
                return;
            }
            
            pagination.style.display = 'flex';
            document.getElementById('page-number').textContent = `${currentPage} / ${totalPages}`;
            
            const prevButton = document.getElementById('prev-page');
            const nextButton = document.getElementById('next-page');
            
            prevButton.disabled = currentPage === 1;
            nextButton.disabled = currentPage === totalPages;
            
            prevButton.onclick = () => {
                if (currentPage > 1) {
                    currentPage--;
                    searchImages();
                    window.scrollTo(0, 0);
                }
            };
            
            nextButton.onclick = () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    searchImages();
                    window.scrollTo(0, 0);
                }
            };
        }
        
        // 显示加载状态
        function showLoading() {
            loadingContainer.style.display = 'flex';
            imageResults.style.display = 'none';
            noResults.style.display = 'none';
            errorMessage.style.display = 'none';
        }
        
        // 隐藏加载状态
        function hideLoading() {
            loadingContainer.style.display = 'none';
        }
        
        // 显示错误信息
        function showError(message) {
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
            imageResults.style.display = 'none';
            noResults.style.display = 'none';
        }
        
        // 显示无结果信息
        function showNoResults() {
            noResults.style.display = 'block';
            imageResults.style.display = 'none';
            errorMessage.style.display = 'none';
        }
        
        // 检查URL参数中是否有搜索关键词
        const urlParams = new URLSearchParams(window.location.search);
        const queryParam = urlParams.get('q');
        if (queryParam) {
            searchInput.value = queryParam;
            performSearch();
        }
    });
</script>
{% endblock %} 